from django.shortcuts import render
from django.http import HttpResponse
from django.urls import reverse
from ..models import User
## 对密码进行加密解密的操作
from django.contrib.auth.hashers import make_password, check_password
## 数据进行复杂的查询
from django.db.models import Q
## 数据分页
from django.core.paginator import Paginator


#  后台页面登录
def login(request):
	if request.method == 'GET':

		return render(request,'myadmin/login.html')
	if request.method == 'POST':
		# 进行登录验证
		# 先进行验证码的验证
		data = request.POST.dict()
		# vcode = data['vcode']
		# if vcode.upper() != request.session['verifycode'].upper():
		# 	url = reverse('login')
		# 	return HttpResponse(f'<script>alert("验证码错误");location.href="{url}";</script>')
		# 获取数据
		ob = User.objects.filter(username=data['username'])
		# 验证用户名；如果状态status为2有管理权限
		if ob:
			ob = ob[0]
			# 对密码进行验证
			if check_password(data['password'],ob.password):
				# 验证用户的权限；是否为管理员权限，即status=2
				print(ob.status)
				if ob.status == 2:
					# 进行登录到后台主页
					return HttpResponse('<script>alert("登陆成功");location.href="/admin/";</script>')
				else:
					return HttpResponse('<script>alert("没有管理员权限");location.href="/admin/login/";</script>')
			else:
				return HttpResponse('<script>alert("密码错误");location.href="/admin/login/";</script>')
		else:
			return HttpResponse('<script>alert("用户名不存在");location.href="/admin/login/";</script>')


# 后台管理首页
def index(request):

	return render(request,'myadmin/index.html')

# 用户列表展示页面
def user_list(request):
	## 搜索设置
	types = request.GET.get('types',None)
	keywords = request.GET.get('keywords',None)
	# 对搜索的性别进行判断
	if keywords == '男':
				keywords = 1
	elif keywords == '女':
		keywords = 0
	## 进行查询条件判断
	if types:
		if types == 'all':
			ob = User.objects.filter(Q(username__contains=keywords)|Q(phone__contains=keywords)|Q(age__contains=keywords)|Q(sex__contains=keywords))
		if types == 'username':
			ob = User.objects.filter(username__contains=keywords)
		if types == 'phone':
			ob = User.objects.filter(phone__contains=keywords)
		if types == 'sex':
			ob = User.objects.filter(sex__contains=keywords)
		if types == 'age':
			ob = User.objects.filter(age__contains=keywords)
	# 获取用户所有数据
	else:
		ob = User.objects.exclude(status=3)
	# 对数据进行分页操作
	paginator = Paginator(ob,2)
	# 获取当前页码
	p = int(request.GET.get('p',1))
	# 获取分页数据对象
	data = paginator.page(p)
	# 分配数据
	content = {'data':data}
	return render(request,'myadmin/user/list.html',content)
	

# 用户列表添加
def user_add(request):
	## 获取请求的方式：request.method
	#判断请求的方式
	if request.method == 'GET':
		return render(request,'myadmin/user/add.html')
	## POST为表单提交数据
	if request.method == 'POST':
		## 接收提交的数据
		data = request.POST.dict()
		data.pop('csrfmiddlewaretoken')
		## 对密码进行加密操作
		data['password'] = make_password(data['password'], None, 'pbkdf2_sha256')
		## 数据的存储
		try:
			ob = User(**data)
			ob.save()
			url = reverse('user_list')
			return HttpResponse(f'<script>alert("添加成功");location.href="{url}";</script>')
		except:
			pass
		url = reverse('user_add')
		return HttpResponse('<script>alert("添加失败");location.href="{url}";</script>')
		

# 用户列表修改
def user_edit(request):
	if request.method == 'GET':
		uid = request.GET.get('id')
		# 获取需要修改的内容
		data = User.objects.get(id=uid)
		content = {'data':data}
		return render(request,'myadmin/user/edit.html',content)
	if request.method == 'POST':
		try:
			data = request.POST.dict()
			# 内容存储
			ob = User.objects.get(id=data['id'])
			ob.phone = data['phone']
			ob.email = data['email']
			ob.age = data['age']
			ob.sex = data['sex']
			ob.save()
			# 跳转
			url = reverse('user_list')
			return HttpResponse(f'<script>alert("编辑成功");location.href="{url}";</script>')
		except:
			pass
		url = reverse('user_edit')
		return HttpResponse(f'<script>alert("编辑失败");location.href="{url}";</script>')
		

# 用户列表删除
def user_del(request,uid):
	# uid要执行删除的字段的id
	# 执行物理删除
	# ob = User.objects.get(id=uid)
	# ob.delete()
	# 执行逻辑删除;将用户的状态改为status=3即可
	ob = User.objects.get(id=uid)
	ob.status = 3
	ob.save()
	# 页面跳转
	url = reverse('user_list')
	return HttpResponse(f'<script>alert("删除成功");location.href="{url}";</script>')

# 用户状态修改
def user_status(request):
	data = request.GET.dict()
	# 获取用户信息
	ob = User.objects.get(id=data['uid'])
	# 状态修改
	ob.status = data['status']
	# 提交
	ob.save()
	return HttpResponse('....')




# ## 定义验证码
# def verifycode(request):
# 	# 引入绘图模块
# 	# Image表示画布对象
# 	# ImageDraw表示画笔对象
# 	# ImageFont表示字体对象
# 	from PIL import Image,ImageDraw,ImageFont
# 	# 引入随机函数模块
# 	import random
# 	# 定义画面的背景色，宽，高
# 	bgcolor = (random.randrange(20,100), random.randrange(20,100),255)
# 	width = 100
# 	height = 30
# 	# 创建画面对象
# 	image = Image.new('RGB',(width,height),bgcolor)
# 	# 创建画笔对象
# 	draw = ImageDraw.Draw(image)
# 	# 绘制噪点
# 	for i in range(0,100):
# 		xy = (random.randrange(0,width),random.randrange(0,height))
# 		fill = (random.randrange(0,255),255,random.randrange(0,255))
# 		draw.point(xy,fill=fill)
# 	# 定义验证码可以出现的值
# 	str1 = 'ABCD123EFGHIJK456LMNOPQRS789TUVWXYZ0'
# 	# 随机获取四个作为验证码
# 	rand_str = ''
# 	for i in range(0,4):
# 		rand_str += str1[random.randrange(0,len(str1))]
# 	# 构造字体对象
# 	font = ImageFont.truetype('FreeMono.ttf',24)
# 	# 构造字体的颜色
# 	draw.text((5,2),rand_str[0],font=font,fill=fontcolor)
# 	draw.text((25,3),rand_str[1],font=font,fill=fontcolor)
# 	draw.text((50,2),rand_str[2],font=font,fill=fontcolor)
# 	draw.text((75,4),rand_str[3],font=font,fill=fontcolor)
# 	# 释放画笔
# 	del draw
# 	# 将获取到的验证码存入session中进行验证
# 	request.session['verifycode'] = rand_str
# 	# 内存文件操作
# 	import io
#     buf = io.BytesIO()
#     #将图片保存在内存中，文件类型为png
#     image.save(buf, 'png')
#     #将内存中的图片数据返回给客户端，MIME类型为图片png
#     return HttpResponse(buf.getvalue(), 'image/png')
